package com.ruoyi.biz.letter.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Objects;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.StrUtil;
import com.google.common.collect.Lists;
import com.ruoyi.biz.export.enums.ExportTemplateEnum;
import com.ruoyi.biz.letter.domain.BizLetterClaim;
import com.ruoyi.biz.letter.mapper.BizLetterClaimMapper;
import com.ruoyi.biz.letter.util.AcceptDeptUtil;
import com.ruoyi.biz.letter.util.CategoryUtil;
import com.ruoyi.biz.letter.util.SysDeptUtil;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.enums.LetterStatus;
import com.ruoyi.common.enums.YesNoStatus;
import com.ruoyi.common.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.biz.letter.mapper.BizCityLetterMapper;
import com.ruoyi.biz.letter.domain.BizCityLetter;
import com.ruoyi.biz.letter.service.IBizCityLetterService;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 地市信访Service业务层处理
 *
 * @author Fei.Cong
 * @date 2024-07-12
 */
@Service
public class BizCityLetterServiceImpl extends ServiceImpl<BizCityLetterMapper, BizCityLetter> implements IBizCityLetterService {

    @Autowired
    private BizCityLetterMapper bizCityLetterMapper;

    @Autowired
    private BizLetterClaimMapper bizLetterClaimMapper;

    /**
     * 分页查询地市信访
     *
     * @param page
     * @param bizCityLetter 地市信访
     */
    @Override
    @DataScope(deptAlias = "t", userAlias = "t")
    public IPage<BizCityLetter> pageList(BizCityLetter bizCityLetter, IPage<BizCityLetter> page) {
        return getPageList(bizCityLetter, page);
    }

    @Override
    @DataScope(deptAlias = "t", userAlias = "t")
    public IPage<BizCityLetter> noPermissionPageList(BizCityLetter bizCityLetter, IPage<BizCityLetter> page) {
        if (StrUtil.isNotBlank(bizCityLetter.getStatus())) {
            switch (bizCityLetter.getStatus()) {
                case "1":
                    bizCityLetter.setStatusList(Lists.newArrayList("1"));
                    break;
                case "2":
                    bizCityLetter.setStatusList(Lists.newArrayList("2", "3"));
                    break;
                case "3":
                    bizCityLetter.setStatusList(Lists.newArrayList("3"));
                    break;
                case "4":
                    bizCityLetter.setStatusList(Lists.newArrayList("4"));
                    break;
                default:
                    break;
            }
        }
        return getPageList(bizCityLetter, page);
    }

    private IPage<BizCityLetter> getPageList(BizCityLetter bizCityLetter, IPage<BizCityLetter> page) {
        bizCityLetter.setDeptIdList(SysDeptUtil.getChildList(bizCityLetter.getDeptId()));
        IPage<BizCityLetter> resultPage = bizCityLetterMapper.selectPageList(page, bizCityLetter);
        for (BizCityLetter record : resultPage.getRecords()) {
//            record.setDeptName(SysDeptUtil.getDept(record.getDeptId()).getDeptName());
//            record.setArea(SysDeptUtil.getUserDept(record.getCreateBy()).getDeptName());
            record.setFirstCategoryName(CategoryUtil.getCacheCategory(record.getPCategoryId()));
            record.setSecondCategoryName(CategoryUtil.getCacheCategory(record.getSCategoryId()));
        }
        return resultPage;
    }

    @Override
    @DataScope(deptAlias = "t", userAlias = "t")
    public List<BizCityLetter> queryDeptList(BizCityLetter bizCityLetter) {
        return bizCityLetterMapper.selectDeptList(bizCityLetter);
    }

    /**
     * 条件查询地市信访
     *
     * @param bizCityLetter 地市信访
     * @return
     */
    @Override
    public List<BizCityLetter> queryList(BizCityLetter bizCityLetter) {
        LambdaQueryWrapper<BizCityLetter> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(BizCityLetter::getBillMonth, bizCityLetter.getBillMonth());
        lambdaQueryWrapper.gt(CollectionUtil.isNotEmpty(bizCityLetter.getParams()), BizCityLetter::getLetterTime, bizCityLetter.getParams().get("beginLetterTime"));
        lambdaQueryWrapper.lt(CollectionUtil.isNotEmpty(bizCityLetter.getParams()), BizCityLetter::getLetterTime, bizCityLetter.getParams().get("endLetterTime"));
        lambdaQueryWrapper.eq(StrUtil.isNotBlank(bizCityLetter.getLetterPurpose()), BizCityLetter::getLetterPurpose, bizCityLetter.getLetterPurpose());
        lambdaQueryWrapper.eq(StrUtil.isNotBlank(bizCityLetter.getIsVisit()), BizCityLetter::getIsVisit, bizCityLetter.getIsVisit());
        lambdaQueryWrapper.like(StrUtil.isNotBlank(bizCityLetter.getAcceptDept()), BizCityLetter::getAcceptDept, bizCityLetter.getAcceptDept());
        lambdaQueryWrapper.in(BizCityLetter::getStatus, bizCityLetter.getStatusList());
        lambdaQueryWrapper.in(Objects.nonNull(bizCityLetter.getDeptId()), BizCityLetter::getDeptId, SysDeptUtil.getChildList(bizCityLetter.getDeptId()));
        return bizCityLetterMapper.selectList(lambdaQueryWrapper);
    }

    @Override
    public void update(BizCityLetter bizCityLetter) {
        CategoryUtil.buildCategoryId(bizCityLetter);
        AcceptDeptUtil.buildAcceptDept(bizCityLetter);
        switch (ExportTemplateEnum.getType(bizCityLetter.getExportType())) {
            case CLAIM:
                claim(bizCityLetter);
                break;
            case DISPATCH:
                bizCityLetter.setDispatchBy(SecurityUtils.getUsername());
                bizCityLetter.setDispatchTime(new Date());
                bizCityLetter.setStatus(LetterStatus.DISPATCH_SUCCESS.getCode());
                this.updateById(bizCityLetter);
                break;
            default:
                break;
        }
    }

    @Override
    public void back(Long id) {
        BizCityLetter entity = bizCityLetterMapper.selectById(id);
        Validator.validateNotNull(entity, "信访件不存在，请查询！");
//        entity.setPCategoryId(0L);
//        entity.setSCategoryId(0L);
//        entity.setIsReasonable("");
//        entity.setIsLaw("");
//        entity.setStatus(LetterStatus.BACK.getCode());
//        bizCityLetterMapper.updateById(entity);
        entity.setClaimBy(SecurityUtils.getUsername());
        bizCityLetterMapper.updateBack(entity);
    }

    private void claim(BizCityLetter bizCityLetter) {
        BizCityLetter entity = this.getById(bizCityLetter.getId());
        if (StrUtil.isBlank(entity.getClaimBy()) || Objects.equals(SecurityUtils.getUsername(), entity.getClaimBy())) {
            entity.setIsReasonable(bizCityLetter.getIsReasonable());
            entity.setIsLaw(bizCityLetter.getIsLaw());
            entity.setPCategoryId(bizCityLetter.getPCategoryId());
            entity.setSCategoryId(bizCityLetter.getSCategoryId());
            entity.setClaimBy(SecurityUtils.getUsername());
            entity.setClaimTime(new Date());
            entity.setStatus(LetterStatus.CLAIM_SUCCESS.getCode());
            bizCityLetterMapper.updateById(entity);
        } else if (!Objects.equals(SecurityUtils.getUsername(), entity.getClaimBy())) {
            entity.setIsRepeatClaim(YesNoStatus.YES.getCode());
            bizCityLetterMapper.updateById(entity);

            bizLetterClaimMapper.delete(new LambdaQueryWrapper<BizLetterClaim>()
                    .eq(BizLetterClaim::getClaimBy, SecurityUtils.getUsername())
                    .eq(BizLetterClaim::getLetterNumber, bizCityLetter.getLetterNumber()));
            BizLetterClaim claim = new BizLetterClaim();
            claim.setLetterId(entity.getId());
            claim.setClaimBy(SecurityUtils.getUsername());
            claim.setLetterNumber(entity.getLetterNumber());
            claim.setPCategoryId(bizCityLetter.getPCategoryId());
            claim.setSCategoryId(bizCityLetter.getSCategoryId());
            claim.setIsReasonable(bizCityLetter.getIsReasonable());
            claim.setClaimTime(new Date());
            bizLetterClaimMapper.insert(claim);
        }
    }

    @Override
    public boolean checkRepeatClaim(Long id) {
        BizCityLetter entity = this.getById(id);
        if (StrUtil.isNotBlank(entity.getClaimBy())) {
            return Objects.equals(SecurityUtils.getUsername(), entity.getClaimBy());
        }
        return true;
    }

    @Override
    public void reset(List<Long> ids) {

        List<BizCityLetter> cityLetters = this.listByIds(ids);

        for (BizCityLetter cityLetter : cityLetters) {
            try {
                if (Objects.equals(cityLetter.getIsRepeatClaim(), YesNoStatus.YES.getCode())) {
                    int delete = bizLetterClaimMapper.delete(new LambdaQueryWrapper<BizLetterClaim>()
                            .eq(BizLetterClaim::getLetterNumber, cityLetter.getLetterNumber()));
                    this.lambdaUpdate().eq(BizCityLetter::getId, cityLetter.getId())
                            .set(BizCityLetter::getClaimBy, "")
                            .set(BizCityLetter::getClaimTime, null)
                            .set(BizCityLetter::getIsRepeatClaim, null)
                            .set(BizCityLetter::getStatus, LetterStatus.WAIT_CLAIM.getCode())
                            .set(BizCityLetter::getPCategoryId, null)
                            .set(BizCityLetter::getSCategoryId, null)
                            .set(BizCityLetter::getIsReasonable, null)
                            .set(BizCityLetter::getIsSolve, null)
                            .set(BizCityLetter::getIsFinish, null)
                            .update();
                }
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }

    }

}
